package com.xjl.remotelink.client;

import com.xjl.remotelink.BaseThread;
import com.xjl.remotelink.LinkLog;
import com.xujl.task.RxExecutor;
import com.xujl.task.Task;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class ClientThread extends BaseThread {
    private static final String TAG = "ClientThread";
    private int linkPort;
    private ClientCallback mCallback;
    private String data;

    public ClientThread (int linkPort, String data, ClientCallback callback) {
        this.linkPort = linkPort;
        mCallback = callback;
        this.data = data;
    }

    @Override
    public void run () {
        super.run();
        Socket socket = null;
        while (!isExit() && socket == null) {
            try {
                socket = new Socket(InetAddress.getLocalHost(), linkPort);
                PrintWriter printWriter = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                ), true);
                printWriter.println(data);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                LinkLog.e(TAG, "writer: " + System.currentTimeMillis());
                String receiveStr = in.readLine();
                LinkLog.e(TAG, "receive result: " + receiveStr);
                RxExecutor.getInstance().executeUiTask(new Task() {
                    @Override
                    public void onlyRunUiTask () {
                        super.onlyRunUiTask();
                        mCallback.onReceiveData(receiveStr);
                    }
                });
                printWriter.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                mCallback.onException(e);
            }
        }
        LinkLog.e(TAG, "Socket: close");
    }
}
